import java.sql.*;

import javax.swing.JOptionPane;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

public class DBConnector {
	
	private final static String driver = "com.mysql.jdbc.Driver";
	private final static String dbName = "jdbc:mysql://localhost:3306/assetregistry";
	private final static String dbUsername = "root";
	private final static String dbPassword = "1234";

	
	//Use this to create a connection to the database
    public static Connection getConnection(){

        try {
            Class.forName(driver).newInstance();
            Connection conn = (Connection) DriverManager.getConnection(dbName, dbUsername, dbPassword);      
            return conn;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }   
    }
	
    //Use this method to execute a query (SELECT)
    public static ResultSet executeQuery(Connection con, String query){
    	try{
    		Statement stmt = con.createStatement();
			return stmt.executeQuery(query);
    	}
    	catch(Exception e){e.printStackTrace();}
    	
    	return null;
    }
    
    //Use this method to execute an update (INSERT, UPDATE, etc)
    public static void executeUpdate(Connection con, String command){
    	try{
    		Statement stmt = con.createStatement();
			stmt.executeUpdate(command);
			con.close();
    	}
    	catch(MySQLIntegrityConstraintViolationException a){
    		a.printStackTrace();
    	}
    	catch(Exception e){e.printStackTrace(); alertUser("Input Error");}
 
    }
    
    /*Use this method when you're executing a query that will SURELY return ONLY ONE value. 
    	The method always returns this as a String, so just parse accordingly.
    */
    public static String executeQueryWithSingleValue(Connection con, String query)
    {
    	ResultSet rs = executeQuery(con, query);
    	try {
			if(rs.next())
			{
				return String.valueOf(rs.getObject(1));
			}
			else
				return null;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
    	return null;
    }
    
    //Temporary, just for alerting the user when Exceptions occur
    public static void alertUser(String message){
    	JOptionPane.showMessageDialog(null, message, "Error!", JOptionPane.WARNING_MESSAGE);
    }
    
}
